package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"live/models"
)

type LiveController struct {
	beego.Controller
}

func (c *LiveController) Add() {
	name := c.GetString("name")
	profile := c.GetString("profile")
	time_add := c.GetString("time_add")
	time_end := c.GetString("time_end")
	num := c.GetString("num")
	user_num := c.GetString("user_num")
	good_num := c.GetString("good_num")
	var live = models.Live{
		Name:    name,
		Profile: profile,
		TimeAdd: time_add,
		TimeEnd: time_end,
		Num:     num,
		UserNum: user_num,
		GoodNum: good_num,
		Deleted: gorm.DeletedAt{},
	}
	if num == "" || time_add == "" || time_end == "" {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "直播间名称、开始时间、结束时间是必填项",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Create(&live).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "创建失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "创建成功",
		Data: nil,
	}
	c.ServeJSON()

}

func (c *LiveController) List() {
	name := c.GetString("name")
	where := map[string]string{}
	if name != "" {
		where["name"] = name
	}
	var lives []models.Live
	err := models.DB.Where(where).Find(&lives).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "查询展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "查询展示成功",
		Data: lives,
	}
	c.ServeJSON()
}

func (c *LiveController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Live{}, id).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
}
